package com.hk.Mgr.web.controller.app.yingmi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hk.Mgr.web.controller.app.AppPaymentCtrl;
import com.hk.Mgr.web.message.order.PaymentReq;
import com.hk.api.ProcessAPI;
import com.hk.api.exceptions.ValidateException;
import com.hk.app.utils.YingmiOpenAPI;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.DateUtil;
import com.hk.commons.FileUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.enm.YingmiBankType;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.sys.MapHelper;
import com.hk.commons.vo.JsonResult;
import com.hk.commons.vo.yingmi.BindPaymentCodeReq;
import com.hk.commons.vo.yingmi.BindPaymentMethodReq;
import com.hk.commons.vo.yingmi.TerminalRequestDTO;
import com.hk.commons.vo.yingmi.UnbindPaymentReq;
import com.hk.context.PaymentContext;
import com.hk.context.RiskEvaluationContext;
import com.hk.service.order.IPayment;
import com.hk.service.sys.ISysUser;
import com.hk.yingmi.YingmiOpenAPIConstant;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * Created by Antinomy on 17/8/24.
 */
@RestController
@RequestMapping(value = BaseCtrl.App)
public class YingmiPaymentController {

    @Autowired
    private YingmiOpenAPI openAPI;

    @Autowired
    private PaymentContext paymentContext;

    @Autowired
    private IPayment paymentService;

    @Autowired
    private ISysUser userService;

    @Value("${hk.logsBaseUrl}")
    private String logsBaseUrl;

    private Logger logger = LoggerFactory.getLogger(YingmiPaymentController.class);

    @Autowired
    private RiskEvaluationContext riskEvaluationContext;


    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_PAYMENT_BANK_LIST, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult bankList(HttpServletRequest request, String flag) {

        ProcessAPI api = (jsonResult, validate) -> {

            String result = openAPI.sslGet(YingmiOpenAPIConstant.UTILS_GET_PAYMENT_PROVIDERS, null, flag);

            openAPI.processJsonResult(jsonResult,result);
        };

        return api.process(request);
    }

    /**
     *绑定盈米支付前，获取验证码
     * @param request
     * @param bindPayment
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_PAYMENT_VERIFICATION_CODE,method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult verificationCode(HttpServletRequest request, @RequestBody BindPaymentCodeReq bindPayment){
        ProcessAPI api = (jsonResult, validate) -> {

            String result = openAPI.sslPost(YingmiOpenAPIConstant.ACCOUNT_PREPARE_BIND_YINGMI_PAYMENTMETHOD, MapHelper.beanToMap(bindPayment));

            openAPI.processJsonResult(jsonResult,result);
        };

        return api.process(request);
    }

    /**
     *绑定支付方式
     * @param request
     * @param bindPayment
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_PAYMENT_BIND_PAYMENT_METHOD,method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult bindPaymentMethod(HttpServletRequest request, @RequestBody BindPaymentMethodReq bindPayment){
        ProcessAPI api = (jsonResult, validate) -> {
            //先记录到txt文件中
            writeBindPaymentMethod(bindPayment);

            String result = openAPI.sslPost(YingmiOpenAPIConstant.ACCOUNT_CONFIRM_BIND_YINGMI_METHOD, MapHelper.transBean2Map(bindPayment));
            openAPI.processJsonResult(jsonResult,result);

            //绑定成功后，保存数据到HK
            if("200".equals(jsonResult.resultCode )){
                //异步记录信息到HK系统
                try {
                    ExecutorService executor = Executors.newFixedThreadPool(1);
                    Runnable task = () -> {
                        Map<String,Object> ymResult = (Map<String, Object>) jsonResult.result;
                        String accountId = String.valueOf(ymResult.get("accountId"));
                        String paymentMethodId = String.valueOf(ymResult.get("paymentMethodId"));

                        PaymentReq paymentReq= new PaymentReq();
                        paymentReq.setUserId(bindPayment.getUserId());
                        paymentReq.setAccountId(accountId);
                        paymentReq.setAccountName(bindPayment.getAccountName());
                        paymentReq.setIdentityNo(bindPayment.getIdentityNo());
                        paymentReq.setPhone(bindPayment.getPhone());
                        paymentReq.setPaymentNo(bindPayment.getPaymentNo());
                        paymentReq.setPaymentMethodId(paymentMethodId);
                        ResponseBase respon = paymentContext.addCard(paymentReq);
                        //绑定成功，把返回的数据记录到txt文件中
                        bindPaymentMethodSuccessRecord(bindPayment,respon.getMsg(),paymentMethodId,accountId);

                        TerminalRequestDTO terminalReq = new TerminalRequestDTO(request);
                        riskEvaluationContext.syncRiskLevelToYingmi(bindPayment.getUserId(),terminalReq);
                    };
                    executor.execute(task);
                    executor.shutdown();

                } catch (Exception e) {
                    logger.error("save payment info error",e);
                    e.printStackTrace();
                }
            }
        };

        return api.process(request);
    }

    /**
     * 解绑盈米绑定
     * @param request
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_UNBIND_PAYMENT_METHOD,method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult unbindPaymentMethod(HttpServletRequest request,@RequestBody UnbindPaymentReq req){
        ProcessAPI api = (jsonResult, validate) -> {
            String brokerUserId = req.getBrokerUserId();
            String accountId = req.getAccountId();
            String paymentMethodId = req.getPaymentMethodId();
            String userId = req.getUserId();
            String paymentNo = req.getPaymentNo();
            validate.check("brokerUserId",brokerUserId);
            validate.check("accountId",accountId);
            validate.check("paymentMethodId",paymentMethodId);
            validate.check("userId",userId);
            validate.check("paymentNo",paymentNo);

            String result= openAPI.sslPost(YingmiOpenAPIConstant.ACCOUNT_CONFIRM_UNBIND_YINGMI_METHOD,MapHelper.transBean2Map(req));
            openAPI.processJsonResult(jsonResult,result);

            //解绑成功后，再调用本地的解绑接口
            if("200".equals(jsonResult.resultCode )){
                try{
                    //异步保存数据
                    ExecutorService executor = Executors.newFixedThreadPool(1);
                    Runnable task = ()->{
                        ResponseBase unbind = paymentContext.unbindYmCard(userId,paymentNo,paymentMethodId,brokerUserId);
                        //解绑记录
                        unbindPaymentMethodRecord(userId,brokerUserId,accountId,paymentMethodId,unbind.getMsg());
                    };
                    executor.execute(task);
                    executor.shutdown();

                }catch (Exception e){
                    logger.error("unbind yingmi card error",e);
                }
            }
        };
        return api.process(request);
    }


    /**
     * 查询账户已绑定的所有支付方式接口（盈米宝+银行）
     * @param request
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_GET_PAYMENT_METHODS_AND_WALLETSHARES,method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getPaymentMethodsAndWalletShares(HttpServletRequest request,String brokerUserId,String accountId,String paymentMethodId,String walletId){
        ProcessAPI api = (jsonResult, validate) -> {

            Map<String, String> params = new HashMap<>();
            params.put("brokerUserId", brokerUserId);
            params.put("accountId", accountId);

            String result= openAPI.sslGet_ByMap(YingmiOpenAPIConstant.TRADE_GETPAYMENTMETHODS_AND_WALLETSHARES,params,null);
            openAPI.processJsonResult(jsonResult,result);
            coverPaymentMethods(jsonResult,paymentMethodId,walletId);
        };

        return api.process(request);

    }

    /**
     * 查询基金赎回支付列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/yingmiAPI/payment/getRedeemFundPayment",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getRedeemFundPayment(HttpServletRequest request,String brokerUserId,String accountId,String paymentMethodId,String walletId){
        ProcessAPI api = (jsonResult, validate) -> {

            Map<String, String> params = new HashMap<>();
            params.put("brokerUserId", brokerUserId);
            params.put("accountId", accountId);

            String result= openAPI.sslGet_ByMap(YingmiOpenAPIConstant.TRADE_GETPAYMENTMETHODS_AND_WALLETSHARES,params,null);
            openAPI.processJsonResult(jsonResult,result);
            coverPaymentMethods(jsonResult,paymentMethodId,walletId);

            checkAndGenerate(jsonResult,brokerUserId,accountId);

        };

        return api.process(request);

    }

    /**
     * 查询账户已绑定的银行支付方式（银行）
     * @param request
     * @param brokerUserId
     * @param accountId
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_PAYMENT_GET_PAYMENT_METHODS,method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getPaymentMethods(HttpServletRequest request,String brokerUserId,String accountId){
        ProcessAPI api = (jsonResult, validate) -> {

            validate.check("brokerUserId", brokerUserId);
            validate.check("accountId", accountId);

            SysUser user = userService.getByPhoneNum(brokerUserId);
            if(user == null){
                throw new ValidateException("用户不存在");
            }

            Map<String, String> params = new HashMap<>();
            params.put("brokerUserId", brokerUserId);
            params.put("accountId", accountId);

            String result= openAPI.sslGet_ByMap(YingmiOpenAPIConstant.ACCOUNT_GET_PAYMENT_METHODS,params,null);
            openAPI.processJsonResult(jsonResult,result);
            addBankName(jsonResult);

        };

        return api.process(request);

    }



    /**
     * 查询账户已绑定的支付方式接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = YingmiOpenAPIConstant.YINGMI_API_PAYMENT_GET_FUND_SHARES, method = RequestMethod.GET)
    @ResponseBody
    public JsonResult getFundShares(HttpServletRequest request, String brokerUserId, String accountId, String flag) {
        ProcessAPI api = (jsonResult, validate) -> {

            validate.check("brokerUserId", brokerUserId);
            validate.check("accountId", accountId);

            Map<String, String> params = new HashMap<>();
            params.put("brokerUserId", brokerUserId);
            params.put("accountId", accountId);

            String result = openAPI.sslGet_ByMap(YingmiOpenAPIConstant.TRADE_GET_FUND_SHARES, params, flag);

            openAPI.processJsonResult(jsonResult, result);
        };

        return api.process(request);
    }

    /**
     * 补全盈米paymentMethodId
     * @param request
     * @param phones，可以接收数组，例如,1234,23425,252423,34
     * @return
     */
    @RequestMapping(value = "/yingmiAPI/payment/addPaymentMethodId",method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    @ResponseBody
    public JsonResult addPaymentMethodId(HttpServletRequest request, @RequestParam String phones){
        ProcessAPI api = (jsonResult, validate) -> {
            validate.check("phones",phones);

            String[] phoneArray = phones.split(",");
            Map<String,Object> success = new HashMap<>();
            Map<String,Object> fail = new HashMap<>();
            for(String phone :phoneArray){
                SysUser user = userService.getByPhoneNum(phone);
                if(user == null){
                    fail = new HashedMap();
                    fail.put(phone,"用户不存在");
                    continue;
                }

                List<Payment> list = getPayments(phone); //查询paymentId为空的支付方式
                if(list == null || list.isEmpty()){
                    fail.put(phone,"没有要更新的数据");
                    continue;
                }

                //查询accountId
                JSONObject accountObj = getAccountId(user.getRealName(),user.getIdentity());
                if(!accountObj.containsKey("accountId")){
                    fail.put(phone,"盈米accountId不存在");
                    continue;
                }

                //查询支付方式
                String paymentInfoReq = getPaymentInfo(user.getName(),accountObj.getString("accountId"));
                if(!openAPI.isJsonArray(paymentInfoReq)){
                    JSONObject paymentInfoObj = JSONObject.parseObject(paymentInfoReq);
                    fail.put(phone,paymentInfoObj.getString("msg"));
                    continue;
                }

                List<Map<String,String>> paymentInfoList = JSON.parseObject(paymentInfoReq,new TypeReference<List<Map<String,String>>>(){});
                List<String> paymentSuccess = new ArrayList<>();
                List<String> paymentfail = new ArrayList<>();
                //匹配与盈米绑定的支付方式，并补全Id
                handlePaymentMethodId(phone, list, paymentInfoList, paymentSuccess, paymentfail);
                //成功列表里面有数据
                if(!paymentSuccess.isEmpty()){
                    success.put(phone,paymentSuccess);
                }
                //失败列表里面有数据
                if(!paymentfail.isEmpty()){
                    fail.put(phone,paymentfail);
                }
            }

            Map<String,Object> result = new HashMap<>();
            result.put("success",success);
            result.put("fail",fail);
            jsonResult.result = result;
        };

        return api.process(request);
    }

    /**
     * 匹配银行卡号与手机号，保存paymentMethodId
     * @param phone 手机号
     * @param list 要补Id的支付方式列表
     * @param paymentInfoList 盈米查询该用户的绑定银行卡列表
     * @param paymentSuccess 成功放到这里
     * @param paymentfail 失败放到这里
     */
    private void handlePaymentMethodId(String phone, List<Payment> list, List<Map<String, String>> paymentInfoList, List<String> paymentSuccess, List<String> paymentfail) {
        for(Payment payment: list){
            List<Map<String,String>> filter = paymentInfoList.stream()
                    .filter(map ->map.get("paymentNo").contains(payment.getPaymentNo().substring(payment.getPaymentNo().length()-4))
                            && map.get("phone").contains(payment.getPhone().substring(payment.getPhone().length()-4)))
                    .collect(Collectors.toList());

            if(filter.size() != 1){
                addPaymentMethodIdRecord(payment.getId(),phone,filter.size(),null);
                paymentfail.add(payment.getId()+"匹配银行卡数："+filter.size());
                continue;
            }
            String paymentMethodId = filter.get(0).get("paymentMethodId");
            payment.setPaymentMethodId(paymentMethodId);
            paymentService.update(payment);
            addPaymentMethodIdRecord(payment.getId(),phone,1,paymentMethodId);
            paymentSuccess.add(payment.getId()+":"+paymentMethodId);
        }
    }

    /**
     * 根据手机号查询盈米卡ID为空的支付方式
     * @param phone
     * @return
     */
    private List<Payment> getPayments(String phone) {
        HqlFilter hqlFilter = new HqlFilter();
        hqlFilter.addEQFilter("cardStatus",1);
        hqlFilter.addEQFilter("userRegistPhone",phone);
        hqlFilter.addSql("and paymentMethodId is null and supportCompany LIKE '%4'");
        return paymentService.findByFilter(hqlFilter);
    }

    /**
     * 获取银行列表
     * @return
     */
    private Map<String,Map<String,Object>> getBankList(){
        String json = openAPI.sslGet(YingmiOpenAPIConstant.UTILS_GET_PAYMENT_PROVIDERS, null, null);
        Map<String,Map<String,Object>> result = null;
        try {
            List<Map<String, Object>> listMap = JSON.parseObject(json, new TypeReference<List<Map<String,Object>>>(){});
            if(listMap == null || listMap.isEmpty()){
                return null;
            }

            result = new HashMap<>();
            for(Map<String,Object> map :listMap){
                result.put(String.valueOf(map.get("paymentType")),map);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取支付方式，把银行名称也加上
     * @param jsonResult
     */
    private void addBankName(JsonResult jsonResult) {
        if (!"200".equals(jsonResult.resultCode)) {
            return;
        }
        //先查询所有银行卡对应的码
        Map<String, Map<String, Object>> bankList = getBankList();
        List<Map<String, Object>> yingMiResult = (List<Map<String, Object>>) jsonResult.result;
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> map : yingMiResult) {

//            Object bankName = bankList.get(map.get("paymentType")).get("name");
            Object bankName = getBankTypeName(bankList, map.get("paymentType").toString());
            map.put("bankName", bankName);
            result.add(map);
        }
        jsonResult.result = result;

    }


    /**
     * 封装用户的支付方式
     * @param jsonResult
     * @param paymentMethodId 银行支付ID
     * @param walletId 盈米宝支付ID
     */
    private void coverPaymentMethods(JsonResult jsonResult,String paymentMethodId,String walletId){
        if(!"200".equals(jsonResult.resultCode)){
            return;
        }
        //先查询所有银行卡对应的码
        Map<String,Map<String,Object>> bankList = getBankList();

        Map<String,Object> result = new HashMap<>();
        List<Map<String,Object>> resultPaymentMethods = new ArrayList<>();
        List<Map<String,Object>> resultWalletShares = new ArrayList<>();
        Map<String,String> userPaymentMap = new HashMap<>(); //为了盈米宝对应的是哪一张银行卡
        Map<String,String> filterMap = new HashMap<>(); // 为了根据walletId过滤支付方式

        Map<String,Object> yingmiResult = (Map<String,Object>)jsonResult.result;
        List<Map<String,Object>> paymentMethods = (List<Map<String,Object>>)yingmiResult.get("paymentMethods");
        List<Map<String,Object>> walletShares = (List<Map<String,Object>>)yingmiResult.get("walletShares");

        //银行卡支付
        for(Map<String,Object> payment:paymentMethods){
            Map<String,Object> map = new HashMap<>();
            map.putAll(payment);
            String paymentNo = payment.get("paymentNo").toString();
            String paymentType = payment.get("paymentType").toString();

            String bankType = getBankTypeName(bankList, paymentType);

            String bankName = bankType +"(尾号"+paymentNo.substring(paymentNo.length()-4,paymentNo.length())+")";

            map.put("bankName",bankName);

            if (bankList.get(paymentType) != null) {
                map.putAll(bankList.get(paymentType));
            }

            resultPaymentMethods.add(map);

            userPaymentMap.put(payment.get("paymentMethodId").toString(),bankName);
        }

        for(Map<String,Object> wallet:walletShares){
            if(!userPaymentMap.containsKey(wallet.get("paymentMethodId")))  //过滤掉没有对应银行卡的盈米宝
                continue;

            Map<String,Object> map = new HashMap<>();
            map.putAll(wallet);
            map.put("bankName",userPaymentMap.get(wallet.get("paymentMethodId").toString()));
            resultWalletShares.add(map);

            //要过滤的银行卡
            if(StringUtils.isNotBlank(walletId) && walletId.equals(wallet.get("walletId"))){
                filterMap.put(wallet.get("paymentMethodId").toString(),"");
            }
        }

        //过滤walletId或paymentMethodId
        if(StringUtils.isNotBlank(paymentMethodId)){
            resultWalletShares = resultWalletShares.stream().filter(m -> m.get("paymentMethodId").equals(paymentMethodId)).collect(Collectors.toList());
            resultPaymentMethods = resultPaymentMethods.stream().filter(m -> m.get("paymentMethodId").equals(paymentMethodId)).collect(Collectors.toList());
        }else if(StringUtils.isNotBlank(walletId)){
            resultWalletShares =  resultWalletShares.stream().filter(m ->m.get("walletId").equals(walletId)).collect(Collectors.toList());
            resultPaymentMethods = resultPaymentMethods.stream().filter(m -> filterMap.containsKey(m.get("paymentMethodId").toString())).collect(Collectors.toList());
        }

        result.put("paymentMethods",resultPaymentMethods);
        result.put("walletShares",resultWalletShares);
        jsonResult.result = result;
    }

    private String getBankTypeName(Map<String, Map<String, Object>> bankList, String paymentType) {
        Map<String, Object> supportBank = bankList.get(paymentType);

        if(supportBank == null || supportBank.get("name")==null){
            return YingmiBankType.getBankType(paymentType).getValue();
        }

        return supportBank.get("name").toString();
    }

    /**
     * 记录绑定盈米支付的申请记录
     * @param bindPayment
     */
    private void writeBindPaymentMethod(BindPaymentMethodReq bindPayment){
        Long cts = System.currentTimeMillis();
        String fileName = "bindPaymentMethod-"+ DateUtil.transferLongToDate("yyyyMM", cts) + ".txt";
        String path = logsBaseUrl+"/yingmiCardRecord/";
        StringBuilder content = new StringBuilder();
        content.append(DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", cts));
        content.append("----绑卡用户信息:  identity = ").append(bindPayment.getIdentityNo());
        content.append(",accountName = ").append(bindPayment.getAccountName());
        content.append(",paymentNo = ").append(bindPayment.getPaymentNo());
        content.append(",phone = ").append(bindPayment.getPhone());
        content.append(",userId =").append(bindPayment.getUserId());
        content.append(",paymentType = ").append(bindPayment.getPaymentType());
        content.append(",accountId = " ).append(bindPayment.getAccountId());
        content.append("\r\n");
        FileUtil.writeFile(path,fileName,content.toString());
    }

    /**
     * 盈米绑卡成功后记录
     * @param req
     * @param msg 保存到数据库时的结果
     * @param paymentMethodId
     * @param accountId
     */
    private void bindPaymentMethodSuccessRecord(BindPaymentMethodReq req, String msg, String paymentMethodId, String accountId){
        Long cts = System.currentTimeMillis();
        String fileName = "bindPaymentMethodSuccessRecord-"+ DateUtil.transferLongToDate("yyyyMM", cts) + ".txt";
        String path = logsBaseUrl+"/yingmiCardRecord/";
        StringBuilder content = new StringBuilder();
        content.append(DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", cts));
        content.append("----盈米绑卡成功:  userId = ").append(req.getUserId());
        content.append(",paymentMethodId = ").append(paymentMethodId);
        content.append(",accountId = ").append(accountId);
        content.append(",phone = ").append(req.getPhone());
        content.append(",accountName = ").append(req.getAccountName());
        content.append(",paymentType = ").append(req.getPaymentType());
        content.append(",brokerUserId = ").append(req.getBrokerUserId());
        content.append(",identityNo = ").append(req.getIdentityNo());
        content.append(",paymentNo =  ").append(req.getPaymentNo());
        content.append(",保存到HK结果 : ").append(msg);
        content.append("\r\n");
        FileUtil.writeFile(path,fileName,content.toString());
    }

    /**
     * 解绑盈米卡记录
     * @param userId
     * @param brokerUserId
     * @param accountId
     * @param paymentMethodId
     * @param msg 处理结果
     */
    private void unbindPaymentMethodRecord(String userId,String brokerUserId,String accountId ,String paymentMethodId,String msg){
        Long cts = System.currentTimeMillis();
        String fileName = "unbindPaymentMethodRecord-"+ DateUtil.transferLongToDate("yyyyMM", cts) + ".txt";
        String path = logsBaseUrl+"/yingmiCardRecord/";
        StringBuilder content = new StringBuilder();
        content.append(DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", cts));
        content.append("----解绑盈米支付:  userId = ").append(userId);
        content.append(",paymentMethodId = ").append(paymentMethodId);
        content.append(",accountId = ").append(accountId);
        content.append(",phone = ").append(brokerUserId);
        content.append(",result = ").append(msg);
        content.append("\r\n");
        FileUtil.writeFile(path,fileName,content.toString());

    }

    /**
     * 基金赎回，如果只是有银行卡支付方式，就生成一个盈米宝的支付方式
     * @param jsonResult
     * @param brokerUserId
     * @param accountId
     */
    private void checkAndGenerate(JsonResult jsonResult,String brokerUserId,String accountId){
        if(!"200".equals(jsonResult.resultCode)){
            return;
        }

        Map<String,Object> yingmiResult = (Map<String,Object>)jsonResult.result;
        List<Map<String,Object>> paymentMethods = (List<Map<String,Object>>)yingmiResult.get("paymentMethods");
        List<Map<String,Object>> walletShares = (List<Map<String,Object>>)yingmiResult.get("walletShares");

        if(!walletShares.isEmpty() || paymentMethods.isEmpty()){
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("brokerUserId", brokerUserId);
        params.put("accountId", accountId);

        String jsonResp = openAPI.sslGet_ByMap(YingmiOpenAPIConstant.TRADE_GET_WALLET_FUNDS, params, null);
        if(!openAPI.isJsonArray(jsonResp)){
            return;
        }

        Map<String,Object> result = new HashMap<>();
        List<Map<String,Object>> resultWalletShares = new ArrayList<>();
        JSONArray fundsArray = JSON.parseArray(jsonResp);
        JSONObject funds = fundsArray.getJSONObject(0);
        Map<String,Object> waletShare = new HashMap<>();
        waletShare.put("walletId","");
        waletShare.put("fundCode",funds.getString("fundCode"));
        waletShare.put("paymentMethodId",paymentMethods.get(0).get("paymentMethodId"));
        waletShare.put("outputAvailShare","");
        waletShare.put("bankName",paymentMethods.get(0).get("bankName"));
        waletShare.put("totalAvailShare","");
        waletShare.put("withdrawAvailShare","");
        resultWalletShares.add(waletShare);

        result.put("paymentMethods",paymentMethods);
        result.put("walletShares",resultWalletShares);
        jsonResult.result = result;
    }

    /**
     * 查询盈米的accountId
     * @param name
     * @param identity
     * @return
     */
    private JSONObject getAccountId(String name,String identity){
        Map<String, String> params = new HashMap<>();
        params.put("accountName", name.trim());
        params.put("identityNo", identity);
        String response = openAPI.sslGet_ByMap(YingmiOpenAPIConstant.ACCOUNT_GET_ACCOUNT_BY_IDENTITY, params, null);
        return JSON.parseObject(response);
    }

    /**
     * 查询盈米支付
     * @param accountId
     * @return
     */
    private String getPaymentInfo(String brokerUserId,String accountId){
        Map<String, String> params = new HashMap<>();
        params.put("brokerUserId", brokerUserId);
        params.put("accountId", accountId);

        return openAPI.sslGet_ByMap(YingmiOpenAPIConstant.ACCOUNT_GET_PAYMENT_METHODS,params,null);
    }

    /**
     * 保存添加盈米PaymentMethodId记录
     * @param id payment表的ID
     * @param count (表示HK与盈米返回的支付列表想匹配，只有一一对应时才算保存成功)
     * @param paymentMethodId
     */
    private void addPaymentMethodIdRecord(Long id,String phone,Integer count,String paymentMethodId){
        Long cts = System.currentTimeMillis();
        String fileName = "addPaymentMethodIdRecord-"+ DateUtil.transferLongToDate("yyyyMM", cts) + ".txt";
        String path = logsBaseUrl+"/yingmiCardRecord/";
        StringBuilder content = new StringBuilder();
        content.append(DateUtil.transferLongToDate("yyyy-MM-dd HH:mm:ss", cts));
        content.append(",id = ").append(id);
        content.append(",phone = ").append(phone);
        content.append(",status = ").append(count == 1 ?"成功":"失败");
        content.append(",mateCount = ").append(count);
        content.append(",paymentMethodId = ").append(paymentMethodId);
        content.append("\r\n");
        FileUtil.writeFile(path,fileName,content.toString());
    }
}
